<template>
  <el-card class="box-card" style="width: 100%;">
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>CPI分析</el-breadcrumb-item>
      <el-breadcrumb-item>按地区分析</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 表格工具栏-条件查询 -->
    <el-row style="margin: 10px auto 5px auto;">
      <el-col :span="10">
        <!-- 表格 -->
        <el-button class="icon" @click="showPicture(0)">&#xe65f;</el-button>
        <!-- 柱状图 -->
        <el-button class="icon" @click="showPicture(1)">&#xeb96;</el-button>
        <!-- 折线图 -->
        <el-button class="icon" @click="showPicture(2)">&#xeb97;</el-button>
        <!-- 饼图 -->
        <el-button class="icon" @click="showPicture(3)">&#xe621;</el-button>
        <!-- 收藏按钮 -->
        <el-button v-show="!collectFlag" @click="collectDialogFlag = true" class="btn el-icon-star-off"
          style="font-size: 30px;"></el-button>
        <!-- 取消收藏 -->
        <el-button v-show="collectFlag" @click="unCollect()" class="btn el-icon-star-off"
          style="font-size: 30px;color: deepskyblue;"></el-button>
        <!-- 收藏列表 -->
        <el-button @click="collectListFlag=true" class="btn el-icon-collection-tag" style="font-size: 30px;">
        </el-button>
      </el-col>
      <el-col :span="6" :offset="2">
        <span>地区：</span>
        <el-select @change="changeProvince" v-model="query.province" clearable filterable placeholder="请选择">
          <el-option v-for="(item,index) in provinceList" :key="index" :label="item" :value="item">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="6" :offset="0">
        <span>时间：</span>
        <el-select @change="changeTime" v-model="query.time" clearable filterable placeholder="请选择">
          <el-option :value="6" label="最近6个月"></el-option>
          <el-option :value="12" label="最近12个月"></el-option>
          <el-option :value="24" label="最近24个月"></el-option>
        </el-select>
      </el-col>
    </el-row>
    <!-- 显示图表(柱状图、折线图、饼状图) -->
    <div id="typePicture" style="width:500px;height:500px;margin: auto auto;" v-show="flagPicture"></div>
    <!-- 表格组件 -->
    <el-table ref='table' :data="tableData" style="width: 100%;" highlight-current-row @row-click="handleSelectionChange">
      <el-table-column sortable fixed prop="type" label="类别" width="180px">
        <template slot-scope="scope">
          <el-radio v-if="radioFlag" v-model="radioSelected" :label="scope.row.type"
            @change.native="handleSelectionChange(scope.row)">
          </el-radio>
          <span v-if="!radioFlag">{{scope.row.type}}</span>
        </template>
      </el-table-column>
      <el-table-column sortable v-for="(item,index) in timeList" :prop="item" :key="index" :label="item" width="180px" :value="item">
      </el-table-column>
    </el-table>
    <!-- 收藏夹弹窗-->
    <el-dialog title="收藏表格" :visible.sync="collectDialogFlag" width="40%">
      <el-form :model="form">
        <el-form-item label="名  称" :label-width="formLabelWidth">
          <el-input v-model="query.collectname" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="collectDialogFlag = false">取 消</el-button>
        <el-button type="primary" @click="collecting()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 收藏列表抽屉-->
    <el-drawer title="收藏列表" :wrapperClosable="false" :visible.sync="collectListFlag" direction="rtl">
      <el-main>
        <el-radio-group v-for="item in listForm" :key="item.id" v-model="collectionId" style="display: block;">
          <el-radio :label="item.id" style="padding-bottom: 15px;">
            <el-tag>
              {{item.collectname}}
            </el-tag>
            <span>
              &nbsp;&nbsp;{{item.province}}-----最近{{item.time}}个月
            </span>
          </el-radio>
        </el-radio-group>
      </el-main>

      <el-footer>
        <el-button @click="collectListFlag = false">取 消</el-button>
        <el-button type="primary" @click="updatePage()">确 定</el-button>
      </el-footer>
    </el-drawer>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        tableData: [],
        query: {
          province: '全国',
          time: 6,
          type: "",
          collectname: ""
        },
        timeList: [], //后端传递的属性名（时间名）
        provinceList: [],
        valueList: [], //后端传递的属性值（时间对应的cpi）
        pieList: [], //饼图显示的list
        flagPicture: 0,
        min: 97,
        max: 108,
        radioFlag: null,
        radioSelected: null,
        //收藏夹
        collectDialogFlag: false, //收藏夹弹窗显示
        form: {
          name: '',
          collections: '',
        },
        formLabelWidth: '50px',
        collectFlag: false, //false未收藏，true已收藏
        // 收藏列表
        collectListFlag: false, //收藏列表（抽屉）显示
        collectionId: 0,
        listForm: [], //收藏列表的所有对象
      }
    },
    methods: {
      //取消收藏
      unCollect() {
        this.$http.post('apis/collection/delete', this.query)
          .then(res => {
            this.collectFlag = false
            this.$message({
              message: '取消收藏成功！！',
              type: 'success'
            });
            this.listCollection()
          })
      },
      // 添加收藏记录
      collecting() {
        this.$http.post('apis/collection/collecting', this.query)
          .then(res => {
            this.collectFlag = true
            this.collectDialogFlag = false;
            this.$message({
              message: '收藏成功！！',
              type: 'success'
            });
            this.listCollection()
          })
      },
      handleSelectionChange(val) {
        let propertyArr = this.timeList
        for (let i = 0; i < this.timeList.length; i++) {
          let x = propertyArr[i]
          this.valueList[i] = val[x]
        }
        this.min = Math.floor(Math.min.apply(null, this.valueList)) - 1
        this.max = Math.ceil(Math.max.apply(null, this.valueList)) + 1
        this.showPicture(this.flagPicture)
      },
      showPicture(flag) {
        this.flagPicture = flag
        let myEcharts = this.$echarts.init(document.getElementById(("typePicture")))
        myEcharts.clear();
        let option = {};
        if (flag === 0) {
          this.radioFlag = false
          return;
        } else if (flag == 1) {
          this.radioFlag = true
          option = {};
          option = {
            tooltip: {
              trigger: 'axis',
              position: function(point, params, dom, rect, size) {
                //  size为当前窗口大小
                if ((size.viewSize[0] / 2) >= point[0]) {
                  //其中point为当前鼠标的位置
                  return [point[0] + 50, '10%'];
                } else {
                  //其中point为当前鼠标的位置
                  return [point[0] - 200, '10%'];
                }
              }
            },
            xAxis: {
              type: 'category',
              data: this.timeList
            },
            yAxis: {
              min: this.min,
              max: this.max,
              interval: 1,
              type: 'value'
            },
            series: [{
              data: this.valueList,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(180, 180, 180, 0.2)'
              }
            }]
          };
        } else if (flag === 2) {
          this.radioFlag = true
          option = {};
          option = {
            tooltip: {
              trigger: 'axis',
              position: function(point, params, dom, rect, size) {
                //  size为当前窗口大小
                if ((size.viewSize[0] / 2) >= point[0]) {
                  //其中point为当前鼠标的位置
                  return [point[0] + 50, '10%'];
                } else {
                  //其中point为当前鼠标的位置
                  return [point[0] - 200, '10%'];
                }
              }
            },
            xAxis: {
              type: 'category',
              data: this.timeList
            },
            yAxis: {
              min: this.min,
              max: this.max,
              interval: 1,
              type: 'value'
            },
            series: [{
              data: this.valueList,
              type: 'line'
            }]
          };
        } else if (flag === 3) {
          this.radioFlag = true
          option = {};
          option = {
            tooltip: {
              trigger: 'item',
            },
            legend: {
              top: '5%',
              left: 'center'
            },
            series: [{
              name: 'CPI',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '40',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: this.pieList
            }]
          };
        }
        myEcharts.clear();
        myEcharts.setOption(option, true);
      },
      // 用户定义的前端请求方法
      listPage() {
        this.$http.get('apis/cpi/bytype', {
          params: {
            province: this.query.province,
            time: this.query.time
          }
        }).then(res => {
          this.valueList = []
          let arr = Object.getOwnPropertyNames(res.data[0])
          arr = arr.filter((item) => {
            return item != 'type';
          });
          this.timeList = arr.sort((a, b) => a < b ? 1 : a > b ? -1 : 0)
          this.tableData = res.data;
          this.radioSelected = this.tableData[0]["type"]
          //获取时间线list所对应的cpilist
          for (let i = 0; i < this.timeList.length; i++) {
            let x = this.timeList[i]
            this.valueList[i] = res.data[0][x]
          }
          //柱状图和折线图的最大值最小值
          this.min = Math.floor(Math.min.apply(null, this.valueList)) - 1
          this.max = Math.ceil(Math.max.apply(null, this.valueList)) + 1
          this.pieList = [];
          //获取饼图显示的数据格式
          for (let i = 0; i < this.timeList.length; i++) {
            this.pieList.push({
              name: this.timeList[i],
              value: this.valueList[i]
            });
          }
          this.showPicture(this.flagPicture)
        })
        this.isCollect()
        //table显示错位问题
        this.$nextTick(() => {
              // table是表格的ref属性值
              if (this.$refs.table && this.$refs.table.doLayout) {
                this.$refs.table.doLayout();
              }
        })
      },
      // 当前选项是否被收藏
      isCollect() {
        this.$http.get('apis/collection/isType', {
          params: {
            province: this.query.province,
            time: this.query.time
          }
        }).then(res => {
          this.collectFlag = res.data ? true : false;
        })
      },
      // 渲染收藏列表
      listCollection() {
        this.listForm = []
        this.$http.get('apis/collection/selectType').then(res => {
          // console.log(res.data)
          this.listForm = res.data;
        })
      },
      listProvince() {
        this.$http.get('apis/cpi/allprovince').then(res => {
          this.provinceList = res.data;
        })
      },
      changeTime() {
        this.listPage()
      },
      changeProvince() {
        this.listPage()
      },
      // 跳转对应的收藏表格
      updatePage() {
        // console.log(this.collectionId)
        // 连接后端获取收藏的地区和时间段
        this.$http.get('apis/collection/getByid', {
          params: {
            id: this.collectionId
          }
        }).then(res => {

          console.log(this.collectionId)
          this.query.time = res.data[0].time
          this.query.province = res.data[0].province
          console.log(this.query.province)
          this.listPage()
          this.$message({
            message: '跳转成功！！',
            type: 'success'
          });
          this.collectListFlag = false; //收藏列表（抽屉）不显示
        })
      },
    },
    mounted() {
      this.listPage()
      this.listProvince()
      this.listCollection()
    },
    updated() {
        // table是表格的ref属性值
        if (this.$refs.table && this.$refs.table.doLayout) {
          this.$refs.table.doLayout();
        }
    }
  }
</script>

<style scoped>
  .icon,
  .btn {
    border: 0px;
    padding: 10px;
  }
</style>
